package bluejack.game.engine;
import bluejack.operation.DelayOper;
import bluejack.operation.FunctionOper;
import bluejack.operation.Oper;
import bluejack.operation.Queue;
import bluejack.operation.URLLoadOper;
import bluejack.text.TextUtil;
import hscript.Interp;
import hscript.Parser;
import nme.errors.Error;
import nme.events.Event;
import nme.events.IOErrorEvent;
import nme.events.ProgressEvent;
import nme.Lib;
import nme.net.URLLoader;
import nme.net.URLRequest;

/**
 * ...
 * @author BlueJack
 */

class ScriptManager 
{
	public var interp(get_interp, null):Interp;
	
	public static function getInstance():ScriptManager {
		if (_instance == null) {
			_instance = new ScriptManager();
			_created = true;
		}
		return _instance;
	}

	public function new() {
		if (_created == true) throw new Error("Singleton Error!");
		_parser = new Parser();
		_interp = new Interp();
		_interp.variables.set("GE", GE);
		_interp.variables.set("Lib", Lib);
		_scriptList = new Hash<String>();
		_queue = new Queue();
	}
	
	public function loadScript(path:String):Void {
		var loader:URLLoadOper = new URLLoadOper(path);
		loader.handler = getScript;
		loader.commit(_queue);
	}
	
	private function getScript(data:Dynamic):Void {
		var strArr:Array<String> = Std.string(data).split("<script>");
		strArr.shift();
		while(strArr.length > 1) {
			var scriptName:String = strArr.shift();
			scriptName = TextUtil.removeBR(scriptName);
			var script:String = strArr.shift();
			_scriptList.set(scriptName, script);
		}
		//Lib.trace(_scriptList);
	}
	
	public function doScript(p_name:String):Void {
		var str:String = _scriptList.get(p_name);
		if (str == null) {
			Lib.trace("Script:" + p_name + " not found!");
			new DelayOper(40).commit(_queue);
			new FunctionOper(doScript, [p_name]).commit(_queue);
			return;
		}
		var script = _parser.parseString(str);
		_interp.execute(script);
	}
	
	private static var _instance:ScriptManager;
	private static var _created:Bool = false;
	private var _queue:Queue;
	private var _parser:Parser;
	private var _interp:Interp;
	private var _scriptList:Hash<String>;
	
	private function get_interp():Interp {
		return _interp;
	}
	
	
}